import localforage from "localforage";
import moment from "moment"


export const ccStoreInstance = localforage.createInstance({
    name: "ccStore"
});

export const callOutStoreInstance = localforage.createInstance({
    name: 'callOutStore'
})

// cc保存操作日志，保存1000次
export const ccStore = {
    store: ccStoreInstance,
    autoClear: () => {
        const maxLen = 1000;
        ccStoreInstance.length().then(len => {
            if(len > maxLen) {
                ccStoreInstance.keys().then(keys => {
                    const removeKeys = keys.slice(0, len - maxLen);
                    removeKeys.forEach(key => {
                        ccStoreInstance.removeItem(key);
                    })
                })
            }
        })
    }
}

// 外呼任务问题保存日志,保存一万条记录
export const callOutStore = {
    store: callOutStoreInstance,
    log: (value, key) => {
        try {
            const storeKey = `${moment().format('YYYY-MM-DD HH:mm:ss')}_${key}_${Math.random()}`;
            callOutStore.store.setItem(storeKey, value);
        } catch (error) {
            console.error(error, 'callOutStore.log')
        }
    },
    autoClear: () => {
        const maxLen = 10000;
        callOutStoreInstance.length().then(len => {
            if(len > maxLen) {
                callOutStoreInstance.keys().then(keys => {
                    const removeKeys = keys.slice(0, len - maxLen);
                    removeKeys.forEach(key => {
                        callOutStoreInstance.removeItem(key);
                    })
                })
            }
        })
    }
}

callOutStore.autoClear();
ccStore.autoClear();

window.localStore = {
    ccStore,
    callOutStore
};